<script setup lang="ts">
/**
 *  自定义表格工具组件。使用了@element-plus:2.8.8。
 *  @Author 游王子og
 *  @Date 2025/02/13
 *  @Version 1.0.0
 *
 *  prop:
 *    addVisible: boolean = true: 添加按钮是否显示
 *    editVisible: boolean = true: 编辑按钮是否显示
 *    deleteVisible: boolean = true: 删除按钮是否显示
 *    exportVisible: boolean = true: 导出按钮是否显示
 *    selectedArray: any = []: 选中的数据
 *  emit:
 *    toAdd: (title: string, data: any) => void: 添加按钮点击事件，返回标题和空对象
 *    toEdit: (title: string, data: any) => void: 编辑按钮点击事件，返回标题和selectedArray中第一个对象
 *    toDelete: (ids: string) => void: 删除按钮点击事件，获取selectedArray中对象的id值，使用,拼接
 *    toExport: () => void: 导出按钮点击事件
 */
import {Delete, Download, Edit, Plus} from '@element-plus/icons-vue'
import {ElMessage, ElMessageBox} from 'element-plus'

const props = withDefaults(defineProps<{
  addVisible?: boolean,
  editVisible?: boolean,
  deleteVisible?: boolean,
  exportVisible?: boolean,
  selectedArray?: any, // 选中的数据
  deleteIdProperty?: string // 删除时，id属性名
}>(), {
  addVisible: true,
  editVisible: true,
  deleteVisible: true,
  exportVisible: true,
  selectedArray: [],
  deleteIdProperty: 'id'
})

const emit = defineEmits(['toAdd', 'toEdit', 'toDelete', 'toExport'])
// 处理添加方法
const addFunction = () => {
  emit('toAdd', '新增', {})
}

// 处理编辑方法
const editFunction = () => {
  if (props.selectedArray.length !== 1) {
    ElMessage({
      message: '请选择一条数据进行编辑',
      type: 'warning'
    })
    return
  } // 将对象进行深拷贝
  emit('toEdit', '编辑', JSON.parse(JSON.stringify(props.selectedArray[0])))
}

// 处理删除方法
const deleteFunction = () => {
  if (props.selectedArray.length === 0) {
    ElMessage({
      message: '请选择一条数据进行删除',
      type: 'warning'
    })
    return
  }
  ElMessageBox.confirm(
    '确认要删除吗？',
    '重要提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 将对象中的id取出组成新的数组，然后使用join拼接
    const ids = props.selectedArray.map((item: any) => item[props.deleteIdProperty])
    emit('toDelete', ids.join(','))
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    })
  })
}

const exportFunction = () => {
  emit('toExport')
}
</script>

<template>
  <div class="table-tool-button">
    <el-tooltip content="添加" v-if="addVisible" placement="top">
      <el-button type="success" :icon="Plus" @click="addFunction" circle/>
    </el-tooltip>
    <el-tooltip content="编辑" v-if="editVisible" placement="top">
      <el-button type="primary" :icon="Edit" @click="editFunction" circle/>
    </el-tooltip>
    <el-tooltip content="删除" v-if="deleteVisible" placement="top">
      <el-button type="danger" :icon="Delete" @click="deleteFunction" circle/>
    </el-tooltip>
    <el-tooltip content="导出" v-if="exportVisible" placement="top">
      <el-button type="warning" :icon="Download" @click="exportFunction" circle/>
    </el-tooltip>
  </div>
</template>

<style scoped>

</style>
